package com.study.limiter;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 单机版时间窗
 *
 * @author: chenhs
 * @date: Created in 11:41 2020/2/2
 **/
public class TwLimiter {

    private Map<Long, AtomicLong> map = new HashMap<>();

    private long before;

    public TwLimiter(long before) {
        this.before = before;
    }

    public AtomicLong get(Long key) {
        if (!this.map.containsKey(key)) {
            synchronized (map) {
                if (this.map.containsKey(key)){
                    map.put(key, new AtomicLong(0L));
                    // 移除指定秒数之前的计数
                    this.removeBefore(key);
                }
            }
        }
        return this.map.get(key);
    }

    private void removeBefore(Long ckey) {
        for (Long key: this.map.keySet()) {
            if (key + before < ckey) {
                this.map.remove(key);
            }
        }
    }


}
